import React, {useMemo} from 'react';
import {
    CartesianGrid,
    Legend,
    Line,
    LineChart,
    ReferenceLine,
    ResponsiveContainer,
    Tooltip,
    XAxis,
    YAxis
} from 'recharts';
import * as PensionCalc from '../utils/pensionCalculations.js';
import {createTooltipFormatter, formatCurrency, formatYears} from '../utils/chartUtils.jsx';

/**
 * 养老金收支平衡点图表
 * @param {Object} props - 组件属性
 * @param {number} props.currentSalary - 当前税前工资
 * @param {number} props.contributionYears - 缴费年限
 * @param {number} props.localAverageSalary - 当地上年度在岗职工月平均工资
 * @param {number} props.retirementAge - 退休年龄
 * @param {string} props.employmentType - 就业类型（在职/灵活）
 * @param {number} props.baseRate - 灵活就业基准比例
 * @returns {JSX.Element}
 */
const BreakEvenPointChart = ({
                                 currentSalary,
                                 contributionYears,
                                 localAverageSalary,
                                 retirementAge,
                                 employmentType,
                                 baseRate
                             }) => {
    const {data, breakEvenPoint} = useMemo(() => {
        const chartData = [];
        const payoutMonths = PensionCalc.getPayoutMonths(retirementAge);
        let personalIndexedSalary, personalAccountTotal, totalContribution;

        // 针对不同就业类型计算
        if (employmentType === 'employee') {
            // 在职人员
            const contributionIndex = PensionCalc.calculateContributionIndex(currentSalary, localAverageSalary);
            personalIndexedSalary = PensionCalc.calculatePersonalIndexedSalary(localAverageSalary, contributionIndex);

            // 限制计算缴费基数在60%-300%之间
            const limitedSalary = Math.max(localAverageSalary * 0.6, Math.min(localAverageSalary * 3, currentSalary));
            personalAccountTotal = PensionCalc.calculateEmployeePAT(limitedSalary, 0.08, contributionYears);
            totalContribution = PensionCalc.calculateEmployeeTotalContribution(limitedSalary, 0.08, contributionYears);
        } else {
            // 灵活就业人员
            personalIndexedSalary = PensionCalc.calculatePersonalIndexedSalary(localAverageSalary, baseRate);
            personalAccountTotal = PensionCalc.calculateFreelancerPAT(localAverageSalary, baseRate, contributionYears);
            totalContribution = PensionCalc.calculateFreelancerTotalContribution(localAverageSalary, baseRate, contributionYears);
        }

        // 计算养老金
        const basicPension = PensionCalc.calculateBasicPension(localAverageSalary, personalIndexedSalary, contributionYears);
        const personalAccountPension = PensionCalc.calculatePersonalAccountPension(personalAccountTotal, payoutMonths);
        const monthlyPension = PensionCalc.calculateMonthlyPension(basicPension, personalAccountPension);

        // 计算收支平衡点
        const breakEvenYears = PensionCalc.findBreakEvenPoint(totalContribution, monthlyPension);

        // 生成图表数据，模拟领取30年的养老金
        const maxYears = Math.max(30, Math.ceil(breakEvenYears) + 5);

        for (let year = 0; year <= maxYears; year++) {
            const receivedPension = PensionCalc.calculateTotalPensionReceived(monthlyPension, year);
            chartData.push({
                year,
                totalContribution,
                receivedPension,
                monthlyPension // 添加月养老金以便在Tooltip中显示
            });
        }

        return {data: chartData, breakEvenPoint: breakEvenYears};
    }, [currentSalary, contributionYears, localAverageSalary, retirementAge, employmentType, baseRate]);

    // 使用通用tooltip格式化器
    const CustomTooltip = createTooltipFormatter({
        formatLabel: (label) => `领取年数: ${label}年`,
        formatters: {
            totalContribution: (value) => formatCurrency(value, false),
            receivedPension: (value) => formatCurrency(value, false),
            monthlyPension: (value) => formatCurrency(value)
        },
        nameMap: {
            totalContribution: '个人缴费总额',
            receivedPension: '养老金领取总额',
            monthlyPension: '月养老金'
        },
        getExtraContent: (payload, label) => {
            // 显示收益率信息
            if (label >= breakEvenPoint) {
                const profit = ((payload[1].value / payload[0].value - 1) * 100).toFixed(2);
                return (
                    <p style={{color: '#ff4d4f', fontWeight: 'bold', marginTop: '8px'}}>
                        收益率: {profit}%
                    </p>
                );
            }
            return null;
        }
    });

    return (
        <div className="chart-container">
            <h3>养老金收支平衡点图表（{formatYears(breakEvenPoint)}）</h3>
            <p className="chart-description">
                本图表展示个人缴费总额与累计领取养老金的关系。<strong>红色垂直虚线</strong>表示收支平衡点（{formatYears(breakEvenPoint)}），
                即养老金领取总额超过个人缴费总额的时间点。此时间点之后，您获得的养老金将超过您的缴费总额，开始获得正收益。
            </p>
            <ResponsiveContainer width="100%" height={400}>
                <LineChart
                    data={data}
                    margin={{
                        top: 20,
                        right: 30,
                        left: 20,
                        bottom: 10,
                    }}
                >
                    <CartesianGrid strokeDasharray="3 3"/>
                    <XAxis
                        dataKey="year"
                        type="number"
                        label={{value: '领取年数（年）', position: 'insideBottomRight', offset: -5}}
                    />
                    <YAxis
                        type="number"
                        label={{value: '金额（元）', angle: -90, position: 'insideLeft'}}
                        tickFormatter={(value) => formatCurrency(value, false)}
                    />
                    <Tooltip content={<CustomTooltip/>}/>
                    <Legend/>
                    <Line
                        type="monotone"
                        dataKey="totalContribution"
                        name="个人缴费总金额"
                        stroke="#8884d8"
                        dot={false}
                    />
                    <Line
                        type="monotone"
                        dataKey="receivedPension"
                        name="养老金领取总金额"
                        stroke="#82ca9d"
                        dot={false}
                    />
                    <ReferenceLine
                        x={breakEvenPoint}
                        stroke="red"
                        strokeWidth={1}
                        strokeDasharray="5 5"
                        label={{value: '收支平衡点', position: 'top', fill: 'red'}}
                        ifOverflow="extendDomain"
                        z={10}
                    />
                </LineChart>
            </ResponsiveContainer>
        </div>
    );
};

export default BreakEvenPointChart; 